<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px;">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        style="height: 400px; overflow-y: hidden;"
        @onCreated="handleCreated"
        @onChange="handleChange"
        @onDestroyed="handleDestroyed"
        @onFocus="handleFocus"
        @onBlur="handleBlur"
        @customAlert="customAlert"
        @customPaste="customPaste"
      />
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadApi } from '@/api/admin'

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: 'default'
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const editorRef = shallowRef(null)

    const valueHtml = ref(props.modelValue)

    watch(
      () => props.modelValue,
      (newValue) => {
        if (newValue !== valueHtml.value) {
          valueHtml.value = newValue || ''
        }
      }
    )

    watch(valueHtml, (newValue) => {
      emit('update:modelValue', newValue)
    })

    const toolbarConfig = {}

    const editorConfig = {
      placeholder: '请输入内容...',
      MENU_CONF: {}
    }

    editorConfig.MENU_CONF.uploadImage = {
      async customUpload(file, insertFn) {
        try {
          const response = await uploadApi.uploadImage(file)

          const url =
            response?.data?.data?.url ||
            response?.data?.url ||
            response?.data?.data?.imageUrl

          if (!url) {
            console.error('上传图片失败：未获取到图片地址', response)
            return
          }

          insertFn(url, '', url)
        } catch (error) {
          console.error('上传图片失败：', error)
        }
      }
    }

    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return

      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor
    }

    const handleChange = (editor) => {
      console.log('change:', editor.getHtml())
    }

    const handleDestroyed = (editor) => {
      console.log('destroyed', editor)
    }

    const handleFocus = (editor) => {
      console.log('focus', editor)
    }

    const handleBlur = (editor) => {
      console.log('blur', editor)
    }

    const customAlert = (info, type) => {
      alert(`【自定义提示】${type} - ${info}`)
    }

    const customPaste = (editor, event, callback) => {
      console.log('ClipboardEvent 粘贴事件对象', event)

      // 获取粘贴的内容
      const clipboardData = event.clipboardData || window.clipboardData;
      const pastedText = clipboardData.getData('text/plain');

      // 将粘贴的文本插入编辑器
      editor.insertText(pastedText)

      // 允许继续粘贴
      callback(true)
    }

    const insertText = () => {
      const editor = editorRef.value
      if (editor == null) return
      editor.insertText('hello world')
    }

    const printHtml = () => {
      const editor = editorRef.value
      if (editor == null) return
      console.log(editor.getHtml())
    }

    const disable = () => {
      const editor = editorRef.value
      if (editor == null) return
      editor.disable()
    }

    return {
      editorRef,
      mode: props.mode,
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleDestroyed,
      handleFocus,
      handleBlur,
      customAlert,
      customPaste,
      insertText,
      printHtml,
      disable
    }
  }
}
</script>
